<?php

namespace app\common\middleware;

use app\Request;
use HugCode\PhpUnits\Frame\Code\ConstCode;
use app\common\services\rbac\UsersServices;
use app\common\services\rbac\UserTokenServices;

class BackstageTokenMiddleware
{

    public function handle(Request $request, \Closure $next)
    {
        $token = $request->header('token', $request->get('token', false));
        //  token 验证
        $result = UserTokenServices::instance()->id($token);
        if ($result === false) {
            _throw('登录异常', 107000);
        }

        /** @var UsersServices $userService */
        $userService = app()->make(UsersServices::class);
        $userInfo    = $userService->get($result['UserID'], ['UserID', 'IsSuper', 'UserStatus']);
        if (empty($userInfo) || $userInfo['UserStatus'] != ConstCode::BASIC_STATUS_NORMAL) {
            _throw('登录异常：当前用户不存在', 107000);
        }

        // 权限验证
        $power = UserTokenServices::instance()->validatorNodePower($userInfo);
        if ($power !== true) {
            _throw('无权限访问接口：' . implode('.', _controller_action()), 107004);
        }

        $request->userId = $result['UserID'];
        return $next($request);
    }

}
